package fourfaith.com.ff_sl21_app.fragment;

import android.app.DatePickerDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fourfaith.com.ff_sl21_app.R;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.DatePickerDialogUtil;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AlarmFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AlarmFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AlarmFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private ImageView query;
    private Button btnSearch;
    private static Context context;
    private AlarmAdapter mAdapter;
    private static SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private LinearLayoutManager mLayoutManager;
    private static LinearLayout load_layout;

    private LinearLayout progressBar, listLayout, dataError, dataEmpty;
    private static List<Map<String, Object>> data = new ArrayList<>();

    private EditText deviceParam;
    private DecimalFormat df = new DecimalFormat("#.###");
    /**
     * 分页信息
     */
    private static int pageStart = 0;
    private static int pageSize = 15;

    /**
     * 日期控件相关
     */
    private DrawerLayout drawerLayout;
    private EditText beginTime;
    private EditText endTime;
    private DatePickerDialog dialog;
    private LinearLayout cancle, complete, cleanTime;
    private int year, monthOfYear, dayOfMonth;
    private SimpleDateFormat timedf = new SimpleDateFormat("yyyy-MM-dd");

    private OnFragmentInteractionListener mListener;
    private static View views;

    public AlarmFragment() {
        // Required empty public constructor
    }

    public static AlarmFragment newInstance(String param1, String param2) {
        AlarmFragment fragment = new AlarmFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_alarm, container, false);
        this.views = view;
        initView(view);
        initQuery(view);
        swipeRefreshLayout.setRefreshing(true);
        getDataRequest();
        return view;
    }

    public void initView(View view) {
        cleanData();
        query = (ImageView) view.findViewById(R.id.query);
        btnSearch = (Button) view.findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Constants.closeKeyBoard(getActivity());
                showLoadingPage();
                cleanData();
                getDataRequest();
            }
        });
        deviceParam = (EditText) view.findViewById(R.id.deviceParam);
        progressBar = (LinearLayout) view.findViewById(R.id.progressBar);
        listLayout = (LinearLayout) view.findViewById(R.id.listLayout);
        dataError = (LinearLayout) view.findViewById(R.id.dataError);
        dataEmpty = (LinearLayout) view.findViewById(R.id.dataEmpty);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        mAdapter = new AlarmAdapter();
        // RecyclerView的ListView模式
        mLayoutManager = new LinearLayoutManager(getActivity());
        // 设置RecyclerView属性为ListView
        recyclerView.setLayoutManager(mLayoutManager);
        // 加载适配器
        recyclerView.setAdapter(mAdapter);
        // 添加滑动监听
        recyclerView.addOnScrollListener(mOnScrollListener);
        //下拉刷新
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);

        // 设置刷新时动画的颜色，可以设置4个
        swipeRefreshLayout.setColorSchemeResources(R.color.blue);

        swipeRefreshLayout.setOnRefreshListener(this);
        drawerLayout = (DrawerLayout) view.findViewById(R.id.drawerLayout);

    }


    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    public void initQuery(View view){

        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.END);
            }
        });
        cancle = (LinearLayout)view.findViewById(R.id.cancle);
        complete = (LinearLayout)view.findViewById(R.id.finish);
        beginTime = (EditText)view.findViewById(R.id.beginTime);
        endTime = (EditText)view.findViewById(R.id.endTime);
        beginTime.setInputType(InputType.TYPE_NULL);
        endTime.setInputType(InputType.TYPE_NULL);
        cleanTime = (LinearLayout)view.findViewById(R.id.cleanTime);

        cancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                drawerLayout.closeDrawer(Gravity.END);
            }
        });

        cleanTime.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                beginTime.setText("");
                endTime.setText("");
            }
        });

        complete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String beginT = beginTime.getText().toString();
                String endT = endTime.getText().toString();

                if(StringUtils.isNotBlank(beginT) || StringUtils.isNotBlank(endT)){

                    if(StringUtils.isBlank(beginT)){
                        new AlertDialog.Builder(context)
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .setTitle("提示信息")
                                .setMessage("请输入开始时间!").show();

                        return;
                    }
                    if(StringUtils.isBlank(endT)){

                        new AlertDialog.Builder(context)
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .setTitle("提示信息")
                                .setMessage("请输入结束时间!").show();

                        return;
                    }

                }

                drawerLayout.closeDrawer(Gravity.END);
                cleanData();
                showLoadingPage();
                getDataRequest();
            }
        });

        //开始时间的监听事件
        beginTime.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                initDate(beginTime);
                dialog = DatePickerDialogUtil.initDialog(getActivity(), year, monthOfYear, dayOfMonth, beginTime);
                dialog.show();
            }

        });
        //结束时间的监听事件
        endTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                initDate(endTime);
                dialog = DatePickerDialogUtil.initDialog(getActivity(), year, monthOfYear, dayOfMonth, endTime);
                dialog.show();
            }
        });

    }

    /**
     * 日期初始化
     */
    private void initDate() {

        //日期初始化
        final Calendar cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);
        monthOfYear = cal.get(Calendar.MONTH)+1;
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        // 设置初始值
        beginTime.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
        endTime.setText(year + "-" + monthOfYear + "-" + dayOfMonth);

    }

    /**
     * 初始化日期
     *
     * @param textView
     */
    private void initDate(EditText textView) {
        String dateStr = textView.getText().toString();
        Calendar cal = Calendar.getInstance();
        try {
            if (dateStr != null && !dateStr.equals("")) {
                cal.setTime(timedf.parse(dateStr));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        year = cal.get(Calendar.YEAR);
        monthOfYear = cal.get(Calendar.MONTH);
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

    }
    /**
     * 数据加载失败显示错误页面
     */
    public void showErrorPage() {
        progressBar.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataError.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);
    }

    /**
     * 数据加载中页面
     */
    public void showLoadingPage() {

        progressBar.setVisibility(View.VISIBLE);
        dataError.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
    }

    /**
     * 数据页面
     */
    public void showDataPage() {

        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.VISIBLE);
        dataEmpty.setVisibility(View.GONE);
    }

    /**
     * 空数据页面
     */
    public void showEmptyPage() {

        progressBar.setVisibility(View.GONE);
        dataError.setVisibility(View.GONE);
        listLayout.setVisibility(View.GONE);
        dataEmpty.setVisibility(View.VISIBLE);
    }

    /**
     * 接口获取数据
     *
     * @return
     */
    private void getDataRequest() {

        String userId = Constants.getUserId();

        String url = null;
        String beginT = beginTime.getText().toString();
        String endT = endTime.getText().toString();
        try {
            url = Constants.alarmList + "?userId=" + userId + "&start=" + pageStart + "&limit=" + pageSize +
                    "&deviceParam=" + URLEncoder.encode(deviceParam.getText() + "", "utf-8")+"&begintime=" + beginT + "&endtime="+endT;
        } catch (Exception e) {
            e.printStackTrace();
        }

        RequestQueue mQueue = RequestQueueSingleton.getInstance(context).getRequestQueue();
        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, url, ResponseResult.class,
                new Response.Listener<ResponseResult>() {
                    @Override
                    public void onResponse(ResponseResult responseResult) {


                        JSONObject dataObj = (JSONObject) responseResult.getData();
                        JSONArray dataArray = dataObj.getJSONArray("list");
                        JSONObject factorMap = dataObj.getJSONObject("factorMap");

                        Map<String, Object> map;

                        if (dataArray != null && dataArray.size() > 0) {
                            for (int i = 0; i < dataArray.size(); i++) {

                                pageStart++;

                                JSONObject model = dataArray.getJSONObject(i);
                                map = new HashMap<>();

                                map.put("id", model.getString("id"));
                                map.put("deviceCode", model.getString("stcd"));
                                String alarmType = model.getString("type");
                                if (alarmType == null) alarmType = "";
                                map.put("alarmType", factorMap.getString(alarmType.toLowerCase()) + "告警");

                                BigDecimal v = model.getBigDecimal("factorvalue");

                                map.put("alarmValue", v == null ? "" : df.format(v.doubleValue()));

                                //0未处理，1已处理
                                map.put("hassolved", model.getString("hassolved"));
                                map.put("alarmTime", model.getString("tm"));

                                data.add(map);
                            }
                        }

                        mAdapter.notifyDataSetChanged();
                        if (data == null || data.size() == 0) {
                            showEmptyPage();
                        } else {
                            showDataPage();
                        }
                        finishRefreshing();
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                finishRefreshing();
                showErrorPage();
                if (error.networkResponse == null) {
                    Toast.makeText(context, "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                } else {
                    if (error.getMessage() == null) {
                        Toast.makeText(context, "接口服务器异常", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }

            }

        });
        mQueue.add(jsonRequest);

    }

    // RecyclerView的滑动监听事件
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        private int lastVisibleItem;

        // 滑动状态改变
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            /**
             * scrollState有三种状态，分别是SCROLL_STATE_IDLE、SCROLL_STATE_TOUCH_SCROLL、SCROLL_STATE_FLING
             * SCROLL_STATE_IDLE是当屏幕停止滚动时
             * SCROLL_STATE_TOUCH_SCROLL是当用户在以触屏方式滚动屏幕并且手指仍然还在屏幕上时
             * SCROLL_STATE_FLING是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
             */
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == mAdapter.getItemCount()
                    && mAdapter.isShowFooter()) {

                load_layout = (LinearLayout) views.findViewById(R.id.load_layout);
                load_layout.setVisibility(View.VISIBLE);
                // 加载更多
                getDataRequest();
            }
        }

        // 滑动位置
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            // 给lastVisibleItem赋值
            // findLastVisibleItemPosition()是返回最后一个item的位置
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
        }
    };

    public static void finishRefreshing() {

        swipeRefreshLayout.setRefreshing(false);
        if (load_layout != null) load_layout.setVisibility(View.GONE);
    }

    class AlarmAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        // 设置底部布局
        private static final int TYPE_FOOTER = 0;
        // 设置默认布局
        private static final int TYPE_DEFAULT = 1;
        // 判断是不是最后一个item，默认是true
        private boolean mShowFooter = true;


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_DEFAULT) {
                View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_alarm_item, parent, false);
                MyViewHolder vh = new MyViewHolder(v);
                return vh;
            } else {
                // 实例化布局
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_footer, null);
                // 代码实现加载布局
                view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                return new FooterViewHolder(view);
            }

        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            // 用来在运行时指出对象是某一个对象
            if (holder instanceof MyViewHolder) {
                Map<String, Object> item = data.get(position);
                if (item == null) {
                    return;
                }

                //数据填充
                ((MyViewHolder) holder).deviceCode.setText(Constants.getString(item.get("deviceCode")));
                ((MyViewHolder) holder).alarmType.setText(Constants.getString(item.get("alarmType")));
                ((MyViewHolder) holder).alarmValue.setText("告警值：" + Constants.getString(item.get("alarmValue")));

                String tm = Constants.getString(item.get("alarmTime"));
                if (tm != null && tm != "") {
                    try {

                        tm = tm.substring(5, tm.length() - 1);
                    } catch (Exception e) {

                    }
                }

                ((MyViewHolder) holder).alarmTime.setText(tm);

                //0未处理，1已处理
                String hassolved = Constants.getString(item.get("hassolved"));

                final String id = String.valueOf(item.get("id"));
                if ("1".equals(hassolved)) {
                    ((MyViewHolder) holder).deal.setVisibility(View.GONE);
                    ((MyViewHolder) holder).cancel.setVisibility(View.VISIBLE);

                } else {
                    ((MyViewHolder) holder).deal.setVisibility(View.VISIBLE);
                    ((MyViewHolder) holder).cancel.setVisibility(View.GONE);
                }

                ((MyViewHolder) holder).deal.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        Map<String, String> params = new HashMap<>();

                        String username = Constants.getUserName();

                        params.put("username", username);
                        params.put("id", id);

                        RequestQueue mQueue = RequestQueueSingleton.getInstance(context).getRequestQueue();
                        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.POST, Constants.alarmSolved, ResponseResult.class,
                                new Response.Listener<ResponseResult>() {
                                    @Override
                                    public void onResponse(ResponseResult responseResult) {

                                        ((MyViewHolder) holder).cancel.setVisibility(View.VISIBLE);
                                        ((MyViewHolder) holder).deal.setVisibility(View.GONE);

                                        Map<String, Object> item = data.get(position);
                                        item.put("hassolved", "1");
                                        data.set(position,item);
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }

                        }, params);
                        mQueue.add(jsonRequest);

                    }
                });

                ((MyViewHolder) holder).cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Map<String, String> params = new HashMap<>();

                        String username = Constants.getUserName();

                        params.put("username", username);
                        params.put("id", id);

                        RequestQueue mQueue = RequestQueueSingleton.getInstance(context).getRequestQueue();
                        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.POST, Constants.alarmSolvedCancel, ResponseResult.class,
                                new Response.Listener<ResponseResult>() {
                                    @Override
                                    public void onResponse(ResponseResult responseResult) {

                                        ((MyViewHolder) holder).deal.setVisibility(View.VISIBLE);
                                        ((MyViewHolder) holder).cancel.setVisibility(View.GONE);


                                        Map<String, Object> item = data.get(position);
                                        item.put("hassolved", "0");
                                        data.set(position,item);
                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }

                        }, params);
                        mQueue.add(jsonRequest);
                    }
                });

            } else {
            /*    if(7==(getItemCount()-1)){
                    ((FooterViewHolder)holder).more_data_msg.setText("已加载全部内容");
                }else{
                    ((FooterViewHolder)holder).more_data_msg.setText("正在加载");
                }*/
            }
        }

        // 设置不同的item
        @Override
        public int getItemViewType(int position) {
            // 判断当前位置+1是不是等于数据总数（因为数组从0开始计数），是的就加载底部布局刷新，不是就加载默认布局
            if (position + 1 == getItemCount()) {
                return TYPE_FOOTER;
            } else {
                return TYPE_DEFAULT;
            }
        }

        @Override
        public int getItemCount() {
            // 判断是不是显示底部，是就返回1，不是返回0
            int begin = mShowFooter ? 1 : 0;
            // 没有数据的时候，直接返回begin
            if (data == null) {
                return begin;
            }
            // 因为底部布局要占一个位置，所以总数目要+1
            return data.size() + begin;

        }

        // 设置是否显示底部加载提示（将值传递给全局变量）
        public void isShowFooter(boolean showFooter) {
            this.mShowFooter = showFooter;
        }

        // 判断是否显示底部，数据来自全局变量
        public boolean isShowFooter() {
            return this.mShowFooter;
        }

        // 底部布局的ViewHolder
        public class FooterViewHolder extends RecyclerView.ViewHolder {
            TextView more_data_msg;

            public FooterViewHolder(View view) {
                super(view);
                more_data_msg = (TextView) view.findViewById(R.id.more_data_msg);

            }
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView deviceCode;
            TextView alarmType;
            TextView alarmValue;
            TextView alarmTime;
            LinearLayout deal, cancel;

            public MyViewHolder(View view) {
                super(view);
                deviceCode = (TextView) view.findViewById(R.id.deviceCode);
                alarmType = (TextView) view.findViewById(R.id.alarmType);
                alarmValue = (TextView) view.findViewById(R.id.alarmValue);
                alarmTime = (TextView) view.findViewById(R.id.alarmTime);
                deal = (LinearLayout) view.findViewById(R.id.deal);
                cancel = (LinearLayout) view.findViewById(R.id.cancel);

            }
        }
    }

    // 设置下拉刷新
    @Override
    public void onRefresh() {
        cleanData();
        mAdapter.notifyDataSetChanged();
        getDataRequest();
    }

    public static void cleanData() {
        pageStart = 0;
        data.clear();
    }


}
